/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.cloud.uaa.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lvyh.lightframe.cloud.authclient.util.JwtUtils;
import com.lvyh.lightframe.cloud.common.constant.SystemConstants;
import com.lvyh.lightframe.cloud.common.model.Result;
import com.lvyh.lightframe.cloud.common.model.SysOauthClient;
import com.lvyh.lightframe.cloud.common.model.SysUser;
import com.lvyh.lightframe.cloud.oauthcenter.api.OauthClientService;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.KeyPair;
import java.security.Principal;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * 认证中心
 */
@RestController
@RequestMapping("/oauth")
@AllArgsConstructor
@Slf4j
public class OAuthController {

    private TokenEndpoint tokenEndpoint;
    private RedisTemplate redisTemplate;
    private KeyPair keyPair;
    private OauthClientService oauthClientService;

    /**
     * OAuth2认证
     * parameters必传项如下:
     * grant_type：授权模式
     * client_id:Oauth2客户端ID（新版本需放置请求头）
     * client_secret:Oauth2客户端秘钥（新版本需放置请求头）
     * refresh_token:刷新token
     * username:登录用户名
     * password:登录密码
     */
    @PostMapping("/token")
    public Object postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {

        String clientId = JwtUtils.getOAuthClientId();
        SysOauthClient sysOauthClient = oauthClientService.getOAuthClientById(clientId);
        String client_secret = sysOauthClient.getClientSecret();
        parameters.put("client_secret", client_secret);
        log.info("OAuth认证授权，客户端ID:{}，请求参数：{}", clientId, JSONUtil.toJsonStr(parameters));
        return Result.succeed(tokenEndpoint.postAccessToken(principal, parameters).getBody());
    }

    /**
     * 微信授权登录,code:小程序授权code
     */
    @PostMapping("/token/{code}")
    public Result wechatLogin(@PathVariable String code, @RequestBody SysUser userInfo) {
        // OAuthToken token = wechatAuthService.login(code, userInfo);
        //  return Result.success(token);
        return null;
    }

    /**
     * 注销
     */
    @DeleteMapping("/logout")
    public Result logout() {
        JSONObject payload = JwtUtils.getJwtPayload();
        String jti = payload.getStr(SystemConstants.JWT_JTI); // JWT唯一标识
        Long expireTime = payload.getLong(SystemConstants.JWT_EXP); // JWT过期时间戳(单位：秒)
        if (expireTime != null) {
            long currentTime = System.currentTimeMillis() / 1000;// 当前时间（单位：秒）
            if (expireTime > currentTime) { // token未过期，添加至缓存作为黑名单限制访问，缓存时间为token过期剩余时间
                redisTemplate.opsForValue().set(SystemConstants.TOKEN_BLACKLIST_PREFIX + jti, null, (expireTime - currentTime), TimeUnit.SECONDS);
            }
        } else { // token 永不过期则永久加入黑名单
            redisTemplate.opsForValue().set(SystemConstants.TOKEN_BLACKLIST_PREFIX + jti, null);
        }
        return Result.succeed("注销成功");
    }

    /**
     * 获取公钥
     */
    @GetMapping("/public-key")
    public Map<String, Object> getPublicKey() {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        return new JWKSet(key).toJSONObject();
    }
}
